import React, { useEffect, useState } from 'react';
import { connect } from 'dva';
import { message, Spin, Modal, Dropdown } from 'antd';
import { getQueryValue, getEnvURL, windowObj, Cookie } from '@/utils/utils';
import { ArrowLeftOutlined } from '@ant-design/icons';
import './index.less';

const sysParam = {
  locat: 'location',
  hf: 'href',
};
// mark isc
const menuMock = [
  // {
  //   key: 1_1,
  //   imgName: 'zfd',
  //   imgName_sel: 'zfd_sel',
  //   auth: '/base',
  //   sys_path: 'base',
  // },
  // {
  //   key: 1_2,
  //   imgName: 'fgw',
  //   imgName_sel: 'fgw_sel',
  //   auth: '/norc',
  //   sys_path: 'norc',
  // },
  // {
  //   key: 2_1,
  //   imgName: 'jxdp',
  //   imgName_sel: 'jxdp_sel',
  //   auth: '/screen',
  //   sys_path: 'screen',
  // },
  {
    key: 1_3,
    imgName: '双碳园区端',
    imgName_sel: 'park',
    auth: '/park',
    sys_path: 'park',
    className: 'marshall2',
  },
  {
    key: 1_4,
    imgName: '电力看能耗',
    imgName_sel: 'energy',
    auth: '/energy',
    sys_path: 'energy',
    className: 'marshall',
  },
  // {
  //   key: 3_1,
  //   imgName: 'yygl',
  //   imgName_sel: 'yygl_sel',
  //   auth: '/system',
  //   sys_path: 'system',
  // },
  // {
  //   key: 2_2,
  //   imgName: 'rzsj',
  //   imgName_sel: 'rzsj_sel',
  //   auth: '/base',
  //   sys_path: 'base',
  //   role: 'rzsj',
  // },
];

const getTicketAuth = (props) => {
  const { dispatch, auth } = props;
  const [loading, setLoading] = useState(true);
  const [menuItem, setMenuItem] = useState([]);
  const [userInfo, setUserInfo] = useState();
  const userInfoItems = {
    items: [
      {
        key: '1',
        label: '退出登录',
        icon: (
          <img
            src={require('@/assets/energy/images/user/quit.png')}
            style={{
              width: '16px',
              height: '16px',
            }}
          />
        ),
      },
    ],
    onClick: usersClick,
  };
  useEffect(() => {
    const tokens = sessionStorage.getItem('author');
    const ticket = getQueryValue('ticket').split('#')[0];

    if (!tokens) {
      if (ticket) {
        dispatch({
          type: 'auth/sysLogin',
          payload: { ticket },
        }).then((res) => {
          const { code, data, auth, tokenUUId } = res;
          // mark isc
          Cookie.set('Authorization', auth, 180, '/base');
          Cookie.set('Authorization', auth, 180, '/norc');
          Cookie.set('Authorization', auth, 180, '/system');
          Cookie.set('Authorization', auth, 180, '/screen');
          Cookie.set('Authorization', auth, 180, '/park');
          Cookie.set('Authorization', auth, 180, '/energy');
          Cookie.set('Authorization', auth, 180, '/');

          if (code && code == 200) {
            debugger
            sessionStorage.setItem('author', auth);
            sessionStorage.setItem('tokenUUId', tokenUUId);
            data && sessionStorage.setItem('authMenu', JSON.stringify(data));
            getAuthMenu(data);
            setLoading(true);
          }
        });
      } else {
        window[sysParam['locat']][sysParam['hf']] = getEnvURL();
      }
    } else {
      setLoading(true);
    }
  }, []);
  useEffect(() => {
    setUserInfo(auth?.userInfo);
  }, [auth?.userInfo]);
  useEffect(() => {
    const menu = sessionStorage.getItem('authMenu');
    if (menu) {
      getAuthMenu(JSON.parse(sessionStorage.getItem('authMenu')));
    }
  }, []);

  const getAuthMenu = (authMenu) => {
    let filterList = [];
    let resultList = [];
    const { route = [], menuTree = [] } = authMenu;
    const govMenu =
      menuTree.find((item) => item.path.includes('base'))?.children || []; // 获取二级菜单
    const isAuditLog = govMenu.find((item) =>
      item.path.toLowerCase().includes('auditlog'),
    );

    if (route) {
      filterList = menuMock.filter((item) => route.includes(item.auth));
      const newlist = filterList.filter((item) =>
        isAuditLog ? item.role : !item.role,
      );
      resultList = newlist;
    }

    setMenuItem(resultList);
  };

  const getSystem = (path, menuData) => {
    sessionStorage.setItem('menuData', JSON.stringify(menuData));
    let url = null;
    const ip = window[windowObj[0]['name']][windowObj[2]['name']];
    // mark isc
    switch (path) {
      case '/base': // 政府端
        url = `${ip}/base/#/`;
        break;
      case '/screen': // 大屏基线版
        url = `${ip}/screen/#/`;
        break;
      case '/norc': // 发改委
        url = `${ip}/norc/#/`;
        break;
      case '/park': // 发改委
        url = `${ip}/park/#/`;
        break;
      case '/energy': //
        url = `${ip}/energy/#/`;
        break;
      default:
        // 管理端
        url = `${ip}/sysment/#/`;
        break;
    }
    return url;
  };

  const [imgType, setImgType] = useState(null);
  const handleMouseOver = (imgName) => {
    setImgType(imgName);
  };
  const handleMouseOut = () => {
    setImgType(null);
  };

  function usersClick(e) {
    if (e.key == 1) {
      handleLoginOut();
    }
  }
  /**
   *
   * @param {*} auth 系统权限
   * @param {*} sys_path 路由权限
   * 当前账号为审计时只能从审计入口进入不可从政府端入口进入。
   * 当前账号为操作员时只能从政府端进入不可从审计入口进入
   *
   */

  const handleImgClick = (params) => {
    if (loading) {
      let isAuth = false;
      const { auth, sys_path, role } = params;
      const authMenu = JSON.parse(sessionStorage.getItem('authMenu'));
      if (authMenu) {
        const { menuTree, route } = authMenu;
        message.destroy();
        if (!route) {
          message.error('获取菜单权限失败');
          return;
        }
        if (route && route.includes(auth)) {
          isAuth = true;
          if (menuTree) {
            const sysMenu = menuTree.filter((item) =>
              item.path.includes(sys_path),
            );
            let menuList = [];
            if (auth !== '/system') {
              //如果不是管理端登录权限返回菜单下二级目录
              menuList =
                sysMenu[0] && sysMenu[0]['children']
                  ? sysMenu[0]['children']
                  : [];
              const isAuditLog = menuList.some((item) =>
                item.path.includes('auditLog'),
              ); // 当前账号是否为审计
              if ((isAuditLog && !role) || (!isAuditLog && role)) {
                isAuth = false;
              }
            } else {
              // 如果返回的是管理端登录权限默认存储返回菜单
              const isPathRouter =
                sysMenu[0] && sysMenu[0]['children']
                  ? sysMenu[0]['children']
                  : [];
              const isAuditLog = isPathRouter.some((item) =>
                item.path.includes('log'),
              ); // 当前账号是否为审计
              if ((isAuditLog && !role) || (!isAuditLog && role)) {
                isAuth = false;
              }
              menuList = sysMenu;
            }

            if (isAuth) {
              window[windowObj[0]['name']][windowObj[1]['name']] = getSystem(
                auth,
                menuList,
              );
            } else {
              isAuth = false;
              message.warning('无该访问系统权限');
            }
          }
        } else {
          isAuth = false;
          message.warning('无该访问系统权限');
        }
      } else {
        message.error('获取菜单权限失败');
      }
    } else {
      message.warning('正在获取菜单权限中。。。');
    }
  };

  const handleLoginOut = () => {
    dispatch({
      type: 'auth/loginOut',
    }).then((res) => {
      if (res.code && res.code == 200) {
        message.success('退出成功');
        sessionStorage.clear();
        Cookie.remove('Authorization');
        setTimeout(() => {
          window[sysParam['locat']][sysParam['hf']] = res.data;
        }, 500);
      } else {
        message.error('退出异常');
      }
    });
  };

  return (
    <div className="sys-go">
      <div className="sys-header">
        <div className="sys-logo">
          <img src={require('@/assets/energy/images/logo-min.png')} alt="" />
          <span>全国碳排放监测分析服务平台</span>
        </div>
        <Dropdown
          menu={{
            ...userInfoItems,
          }}
          placement="bottom"
        >
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              marginRight: '20px',
              cursor: 'pointer',
            }}
            onClick={(e) => e.preventDefault()}
          >
            <img
              src={require('@/assets/energy/images/user/u280.jpg')}
              alt=""
              style={{
                height: '30px',
                width: '30px',
                borderRadius: '50%',
              }}
            />
            <span style={{ marginLeft: '8px' }}>{userInfo?.userName}</span>
          </div>
        </Dropdown>
      </div>
      {loading ? (
        <div>
          {/* <div className="sys-out" onClick={handleLoginOut}>
              退 出<ArrowLeftOutlined />
            </div> */}
          <div className="sys-content-bg">
            <div className="sys-content-main">
              <div className="sys-info">
                <img
                  src={require('@/assets/energy/images/user/u280.jpg')}
                  alt=""
                  style={{
                    width: '6.5rem',
                    height: '6.5rem',
                    marginLeft: '20rem',
                    marginRight: '1rem',
                  }}
                />
                <div>
                  <div className="helloTag">
                    {userInfo?.userName +
                      ' 你好，欢迎使用全国碳排放监测分析服务平台'}
                  </div>
                  <div className="enterprise">
                    <span>xxxx岗位</span> | <span>国网xx省电力公司</span>
                  </div>
                </div>
              </div>
              <div className="menuTag">
                {menuItem.map((item) => (
                  <div>
                    <div
                      className={item?.className}
                      onClick={(e) => handleImgClick(item)}
                    >
                      <img
                        src={require(`../assets/images/${item.imgName_sel}.png`)}
                        alt=""
                        className="imgIcon"
                        style={{
                          width: '2rem',
                          height: '2rem',
                        }}
                      />
                      <div className="tagText">{item.imgName}</div>
                    </div>
                  </div>
                ))}
                {/* <div>
                  <div className="marshall">
                    <img
                      src={require('../assets/images/base.png')}
                      alt=""
                      className="imgIcon"
                      style={{
                        width: '2rem',
                        height: '2rem',
                      }}
                    />
                    <div className="tagText">电力看双碳</div>
                  </div>
                </div>
                <div>
                  <div className="marshall">
                    <img
                      src={require('../assets/images/energy.png')}
                      alt=""
                      className="imgIcon"
                    />
                    <div className="tagText">电力看能耗</div>
                  </div>
                </div>
                <div>
                  <div className="marshall2">
                    <img
                      src={require('../assets/images/park.png')}
                      alt=""
                      className="imgIcon"
                      style={{
                        width: '2rem',
                        height: '2rem',
                      }}
                    />
                    <div className="tagText">双碳园区端</div>
                  </div>
                </div>
                <div>
                  <div className="marshall2">
                    <img
                      src={require('../assets/images/enterprise.png')}
                      alt=""
                      className="imgIcon"
                    />
                    <div className="tagText">双碳企业端</div>
                  </div>
                </div> */}
                <span className="ptImg"></span>
              </div>
            </div>
            {/* {[
                menuItem.slice(0, 2),
                menuItem.slice(2, 4),
                menuItem.slice(4, 6),
              ].map((item, i) => (
                <div className="sys-content-item" key={i}>
                  {item?.map((ls) => (
                    // <img
                    //   src={require(`../assets/images/${
                    //     imgType == ls.imgName_sel ? ls.imgName_sel : ls.imgName
                    //   }.png`)}
                    //   alt=""
                    //   key={ls.key}
                    //   onMouseOver={(e) => handleMouseOver(ls.imgName_sel)}
                    //   onMouseOut={handleMouseOut}
                    //   onClick={(e) => handleImgClick(ls)}
                    // />
                    <div className="sys-out" onClick={(e) => handleImgClick(ls)}>
                      {imgType == ls.imgName_sel ? ls.imgName_sel : ls.imgName}
                    </div>
                  )) || []}
                </div>
              ))} */}
          </div>
        </div>
      ) : (
        <div
          style={{
            width: '100%',
            display: 'flex',
            justifyContent: 'center',
            marginTop: 50,
          }}
        >
          <Spin size="large" />
        </div>
      )}
    </div>
  );
};

export default connect(({ auth }) => ({ auth }))(getTicketAuth);
